package cn.itcast.gateway;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器
 * @author Xiao
 * @date 2021/10/15
 */
@Component
//@Order(-1)  //配置过滤器执行顺序
public class AuthorizationFilter implements GlobalFilter, Ordered {
    /**
     * 登录状态判断：参数中是否有authorization，authorization参数值是否为admin
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        //2.获取authorization参数
        String auth = params.getFirst("authorization");
        // 3.校验
        if ("admin".equals(auth)) {
            //放行
            return chain.filter(exchange);
        }
        // 4.拦截
        // 4.1.禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }

    /**
     * 配置过滤器执行顺序：    -2147483648 —— 2147483647
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
